import React, { useState } from "react";
import {
  Text,
  StyleSheet,
  View,
  Image,
  TextInput,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import { useTranslation } from "react-i18next";
import PageContainer from "@/components/PageContainer";
import { Picker } from "@react-native-picker/picker";
import {
  queryOrderBookFnAPi,
  queryTradeOrderFnAPi,
  orderPlaceFnAPi,
  queryAssetsFnAPi,
  cancelOrderFnAPi,
} from "../api/maret";
import { ToastAPI } from "@/components/Toast";
import { useRouter, useLocalSearchParams } from "expo-router"; // 引入 useRouter

const InputWithButtons = ({
  placeholder,
  value,
  onChange,
  onIncrement,
  onDecrement,
}: {
  placeholder: string;
  value: string | null;
  onChange: (text: string) => void;
  onIncrement: () => void;
  onDecrement: () => void;
}) => {
  return (
    <View className="flex-row items-center mt-[10px] bg-[#23272A] h-[40px] px-[18px] rounded-[5px]">
      <TouchableOpacity onPress={onDecrement}>
        <Text style={{ color: "#478CFE", fontSize: 18 }}>-</Text>
      </TouchableOpacity>
      <TextInput
        value={value as any}
        onChangeText={onChange}
        keyboardType="numeric"
        placeholder={placeholder}
        placeholderTextColor={"rgba(255,255,255,0.3)"}
        style={{
          flex: 1,
          textAlign: "center",
          color: "#fff",
          fontSize: 14,
        }}
      />
      <TouchableOpacity onPress={onIncrement}>
        <Text style={{ color: "#478CFE", fontSize: 18 }}>+</Text>
      </TouchableOpacity>
    </View>
  );
};

// 定义函数式组件
const Category = () => {
  const router = useRouter();
  const params = useLocalSearchParams<any>();
  const { t } = useTranslation();
  const [selectedOption, setSelectedOption] = useState("3");
  const [direction, setDirection] = useState(Number(params?.direction) || 0);
  // 分别管理不同字段的值
  const [price, setPrice] = useState<string | null>(null);
  const [quantity, setQuantity] = useState<string | null>(null);
  const [triggerPrice, setTriggerPrice] = useState<string | null>(null);
  const [entrustPrice, setEntrustPrice] = useState<string | null>(null);
  // 处理输入变化的通用函数
  const handleInputChange =
    (setter: (value: string | null) => void) => (text: string) => {
      setter(text);
    };

  // 处理加操作的通用函数
  const handleIncrement = (
    setter: (value: string | null) => void,
    currentValue: string | null
  ) => {
    const value = currentValue ? parseInt(currentValue, 10) + 1 : 1;
    // 如果值为 0，设置为 null 以清空输入框
    setter(value === 0 ? null : value.toString());
  };

  // 处理减操作的通用函数
  const handleDecrement = (
    setter: (value: string | null) => void,
    currentValue: string | null
  ) => {
    const value = currentValue
      ? Math.max(0, parseInt(currentValue, 10) - 1)
      : 0;
    // 如果值为 0，设置为 null 以清空输入框
    setter(value === 0 ? null : value.toString());
  };

  //切换币种
  const [myPrice, setMyPrice] = useState<any>({});
  const [selectCurrency, setSelectCurrency] = useState<any>({});
  const getCurrencyList = async () => {
    try {
      const res: any = await queryAssetsFnAPi();
      if (res.code === 0) {
        setMyPrice({
          referencePriceAsDollar: res.result?.referencePriceAsDollar,
          referencePriceAsCny: res.result?.referencePriceAsCny,
        });
      } else {
        ToastAPI.error(res?.errMsg || t("common.loadFailed"));
      }
    } catch (error) {
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("common.loadFailed"));
    }
  };
  React.useEffect(() => {
    setSelectCurrency(params);
    getOrderBookAndTrade(params.tradingId);
    getCurrencyList();
    setDirection(Number(params?.direction) || 0);
  }, [params.tradingId]);
  const [orderBook, setOrderBook] = useState<any>({});
  const [tradeOrder, setTradeOrder] = useState([]);
  //获取成交记录和获取订单薄
  const getOrderBookAndTrade = async (tradingPairId: string) => {
    ToastAPI.loading(t("common.loading"), "center", -1);
    try {
      const [orderBookResponse, tradeOrderResponse] = (await Promise.all([
        queryOrderBookFnAPi({ tradingPairId }),
        queryTradeOrderFnAPi({ tradingPairId }),
      ])) as any;
      ToastAPI.close();
      setOrderBook(orderBookResponse?.result || { ask: [], bid: [] });
      setTradeOrder(tradeOrderResponse?.result?.dataList || []);
      return {
        orderBookResponse,
        tradeOrderResponse,
      };
    } catch (error) {
      ToastAPI.error(JSON.stringify(error) || t("common.loadFailed"));
      // 错误时返回 null
      return null;
    }
  };

  // 定义状态映射函数
  const getOrderStatusText = (status: number | undefined) => {
    switch (status) {
      case 0:
        return "待交易";
      case 1:
        return "部分成交";
      case 2:
        return "已完成";
      case 3:
        return "已取消";
      default:
        return "未知状态";
    }
  };
  //交易
  const subOrderPlaceFnAPi = async () => {
    if (selectedOption) {
      let requiredFieldsMissing = false;
      switch (selectedOption) {
        case "1": // 市场单
          if (!quantity) {
            ToastAPI.error("数量不能为空");
            requiredFieldsMissing = true;
          }
          break;
        case "2": // 市场止损单
          if (!triggerPrice && !quantity) {
            ToastAPI.error("触发价和数量不能为空");
            requiredFieldsMissing = true;
          }
          break;
        case "3": // 限价单
          if (!price && !quantity) {
            ToastAPI.error("价格和数量不能为空");
            requiredFieldsMissing = true;
          }
          break;
        case "4": // 限价止损单
          if (!entrustPrice && !triggerPrice && !quantity) {
            ToastAPI.error("委托价、触发价和数量不能为空");
            requiredFieldsMissing = true;
          }
          break;
        default:
          break;
      }
      if (requiredFieldsMissing) {
        return;
      }
    }
    if (selectedOption !== "3") {
      ToastAPI.error("此类型暂未开发");
      return;
    }
    ToastAPI.loading(t("common.loading"), "center", -1);
    try {
      const res: any = await orderPlaceFnAPi({
        memberId: 1,
        tradingPairId: selectCurrency?.tradingId,
        price: price,
        amount: quantity,
        direction, //0买入，1卖出
      });
      ToastAPI.close();
      if (res.code === 0) {
        ToastAPI.success(t("common.success"));
        setQuantity(null);
        setPrice(null);
        setTriggerPrice(null);
        setEntrustPrice(null);
        getOrderBookAndTrade(selectCurrency?.tradingId);
        getCurrencyList();
      } else {
        ToastAPI.error(res?.errMsg || t("common.loadFailed"));
      }
    } catch (error) {
      ToastAPI.close();
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("common.loadFailed"));
    }
  };
  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row justify-between h-[46px]">
          <View className="items-center flex-row h-[46px]">
            <TouchableOpacity onPress={() => router.back()}>
              <View className="flex-row gap-[10px] items-center">
                <Image
                  source={require("@/assets/images/return-left.png")}
                  className="w-[18px] h-[18px]"
                />
                <View className="flex-row items-end gap-[5px]">
                  <Text className="text-[18px] text-[#fff]">
                    {selectCurrency?.mainAssetSymbol}/
                    {selectCurrency?.secondaryAssetSymbol}
                  </Text>
                  <View className="px-[10px] py-[2px] rounded-[5px] bg-[rgba(11,187,115,0.2)]">
                    <Text className="text-[14px] text-[#0BBB73]">
                      {parseFloat(selectCurrency?.changeRatio) < 0 ? "" : "+"}
                      {selectCurrency?.changeRatio}%
                    </Text>
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <View className="flex-1 flex-row justify-center">
              <View className="flex-row items-center"></View>
            </View>
            <View className="w-[18px] h-[18px]"></View>
          </View>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
        >
          <View className="flex-row mt-[22px] items-start gap-[20px] border-b-[1px] border-[#323234]">
            <View>
              <View className="flex-row items-center">
                <TouchableOpacity
                  className="w-[102px] h-[28px] relative"
                  onPress={() => setDirection(0)}
                >
                  <Image
                    source={
                      direction === 0
                        ? require("@/assets/images/beijing.png")
                        : require("@/assets/images/beijing3.png")
                    }
                    className="w-[102px] h-[28px]"
                  />
                  <Text className="absolute text-[14px] text-[#fff] w-[100%] text-center leading-[28px]">
                    买入
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  className="w-[102px] h-[28px] relative"
                  onPress={() => setDirection(1)}
                >
                  <Image
                    source={
                      direction === 0
                        ? require("@/assets/images/beijing1.png")
                        : require("@/assets/images/beijing4.png")
                    }
                    className="w-[102px] h-[28px]"
                  />
                  <Text className="absolute text-[14px] text-[#fff] w-[100%] text-center leading-[28px]">
                    卖出
                  </Text>
                </TouchableOpacity>
              </View>
              <View className="bg-[#23272A] mt-[10px] rounded-[5px] h-[60px]">
                <Picker
                  selectedValue={selectedOption}
                  onValueChange={(itemValue) => setSelectedOption(itemValue)}
                  style={{
                    width: "100%",
                    color: "#fff",
                    fontSize: 14,
                    textAlign: "center",
                  }}
                  mode="dropdown"
                  placeholder="请选择"
                  dropdownIconColor="#888C90"
                >
                  <Picker.Item label="市场单" value="1" />
                  <Picker.Item label="市场止损单" value="2" />
                  <Picker.Item label="限价单" value="3" />
                  <Picker.Item label="限价止损单" value="4" />
                </Picker>
              </View>
              {selectedOption === "1" && (
                <InputWithButtons
                  placeholder="数量"
                  value={quantity}
                  onChange={handleInputChange(setQuantity)}
                  onIncrement={() => handleIncrement(setQuantity, quantity)}
                  onDecrement={() => handleDecrement(setQuantity, quantity)}
                />
              )}
              {selectedOption === "2" && (
                <>
                  <InputWithButtons
                    placeholder="触发价"
                    value={triggerPrice}
                    onChange={handleInputChange(setTriggerPrice)}
                    onIncrement={() =>
                      handleIncrement(setTriggerPrice, triggerPrice)
                    }
                    onDecrement={() =>
                      handleDecrement(setTriggerPrice, triggerPrice)
                    }
                  />
                  <InputWithButtons
                    placeholder="数量"
                    value={quantity}
                    onChange={handleInputChange(setQuantity)}
                    onIncrement={() => handleIncrement(setQuantity, quantity)}
                    onDecrement={() => handleDecrement(setQuantity, quantity)}
                  />
                </>
              )}
              {selectedOption === "3" && (
                <>
                  <InputWithButtons
                    placeholder="价格"
                    value={price}
                    onChange={handleInputChange(setPrice)}
                    onIncrement={() => handleIncrement(setPrice, price)}
                    onDecrement={() => handleDecrement(setPrice, price)}
                  />
                  <InputWithButtons
                    placeholder="数量"
                    value={quantity}
                    onChange={handleInputChange(setQuantity)}
                    onIncrement={() => handleIncrement(setQuantity, quantity)}
                    onDecrement={() => handleDecrement(setQuantity, quantity)}
                  />
                </>
              )}
              {selectedOption === "4" && (
                <>
                  <InputWithButtons
                    placeholder="委托价"
                    value={entrustPrice}
                    onChange={handleInputChange(setEntrustPrice)}
                    onIncrement={() =>
                      handleIncrement(setEntrustPrice, entrustPrice)
                    }
                    onDecrement={() =>
                      handleDecrement(setEntrustPrice, entrustPrice)
                    }
                  />
                  <InputWithButtons
                    placeholder="触发价"
                    value={triggerPrice}
                    onChange={handleInputChange(setTriggerPrice)}
                    onIncrement={() =>
                      handleIncrement(setTriggerPrice, triggerPrice)
                    }
                    onDecrement={() =>
                      handleDecrement(setTriggerPrice, triggerPrice)
                    }
                  />
                  <InputWithButtons
                    placeholder="数量"
                    value={quantity}
                    onChange={handleInputChange(setQuantity)}
                    onIncrement={() => handleIncrement(setQuantity, quantity)}
                    onDecrement={() => handleDecrement(setQuantity, quantity)}
                  />
                </>
              )}
              <View className="items-center flex-row justify-between mt-[10px]">
                <Text className="text-[12px] text-[#8F9093]">可用</Text>
                <Text className="text-[12px] text-[#8F9093]">
                  {myPrice?.referencePriceAsDollar || 0}USDT
                </Text>
              </View>
              <TouchableOpacity
                style={{
                  display: "flex",
                  backgroundColor: direction === 0 ? "#0BBB73" : "#EA4474",
                  borderRadius: 30,
                  paddingVertical: 12,
                  justifyContent: "center",
                  alignItems: "center",
                  marginTop: 10,
                  marginBottom: 10,
                }}
                onPress={() => {
                  subOrderPlaceFnAPi();
                }}
              >
                <Text className="text-[14px] text-[#fff]">
                  {direction === 0 ? "交易" : "出售"}
                </Text>
              </TouchableOpacity>
            </View>
            <View className="flex-1">
              <View className="flex-row items-center justify-between ">
                <View>
                  <Text className="text-[12px] text-[#8F9093]">价格</Text>
                  <Text className="text-[12px] text-[#8F9093]">
                    {selectCurrency?.secondaryAssetSymbol}
                  </Text>
                </View>
                <View>
                  <Text className="text-[12px] text-[#8F9093]">数量</Text>
                  <Text className="text-[12px] text-[#8F9093]">
                    {selectCurrency?.mainAssetSymbol}
                  </Text>
                </View>
              </View>
              {orderBook?.ask?.length > 0 ? (
                orderBook?.ask?.map((item: any, index: any) => {
                  return (
                    <View
                      className="flex-row items-center justify-between mb-[10px]"
                      key={index}
                    >
                      <Text className="text-[12px] text-[#EA4474]">
                        {item.price}
                      </Text>
                      <Text className="text-[12px] text-[#fff]">
                        {item.volume}
                      </Text>
                    </View>
                  );
                })
              ) : (
                <View
                  className="justify-center items-center"
                  style={{ flex: 1 }}
                >
                  <Image
                    source={require("@/assets/images/empty.png")}
                    className="w-[143px] h-[100px]"
                  />
                  <Text className="text-[#fff] text-[14px] mt-[10px]">
                    暂无数据
                  </Text>
                </View>
              )}
              {orderBook?.bid?.length > 0 && (
                <View className="mb-[10px]">
                  <Text className="text-[18px] text-[#0BBB73]">
                    {myPrice?.referencePriceAsDollar || 0}
                  </Text>
                  <Text className="text-[12px] text-[#8F9093]">
                    ≈￥{myPrice?.referencePriceAsCny}
                  </Text>
                </View>
              )}
              {orderBook?.bid?.length > 0 &&
                orderBook?.bid?.map((item: any, index: any) => {
                  return (
                    <View
                      className="flex-row items-center justify-between mb-[10px]"
                      key={index}
                    >
                      <Text className="text-[12px] text-[#0BBB73]">
                        {item.price}
                      </Text>
                      <Text className="text-[12px] text-[#fff]">
                        {item.volume}
                      </Text>
                    </View>
                  );
                })}
            </View>
          </View>
          <View className="mt-[13px]">
            <View className="justify-between items-center flex-row">
              <View className="gap-[10px] items-center flex-row">
                <Image
                  source={require("@/assets/images/rectangle.png")}
                  className="w-[3px] h-[18px]"
                ></Image>
                <Text className="text-[#fff] text-[18px] font-[bold]">
                  交易记录
                </Text>
              </View>
            </View>
          </View>
          <View className="mt-[22px] flex-row justify-between items-center">
            <Text className="text-[14px] text-[#949494]">类别</Text>
            <Text className="text-[14px] text-[#949494]">成交量</Text>
            <Text className="text-[14px] text-[#949494]">价格（CNY）</Text>
            <Text className="text-[14px] text-[#949494]">状态</Text>
          </View>
          {tradeOrder?.length > 0 ? (
            tradeOrder?.map((item: any, index: any) => {
              return (
                <View
                  className="mt-[10px] flex-row justify-between items-center"
                  key={index}
                >
                  <Text className="text-[14px] text-[#fff]">
                    {item?.orderAction == 0 ? "卖出" : "买入"}
                  </Text>
                  <Text className="text-[14px] text-[#fff]">
                    {item?.dealAmount}
                  </Text>
                  <Text className="text-[14px] text-[#fff]">{item?.price}</Text>
                  <TouchableOpacity
                    onPress={() => {
                      if (item?.orderStatus === 0) {
                        Alert.alert("确认撤销", "确定要撤销该订单吗？", [
                          { text: "取消", style: "cancel" },
                          {
                            text: "确认",
                            onPress: () => {
                              cancelOrderFnAPi({
                                orderId: item?.id,
                                memberId: "0",
                              }).then(() => {
                                item.orderStatus = 3;
                                ToastAPI.success("撤销成功");
                              });
                            },
                          },
                        ]);
                      }
                    }}
                  >
                    <Text className="text-[14px] text-[#fff]">
                      {getOrderStatusText(item?.orderStatus)}
                    </Text>
                  </TouchableOpacity>
                </View>
              );
            })
          ) : (
            <View className="justify-center items-center" style={{ flex: 1 }}>
              <Image
                source={require("@/assets/images/empty.png")}
                className="w-[143px] h-[100px]"
              />
              <Text className="text-[#fff] text-[14px] mt-[10px]">
                暂无数据
              </Text>
            </View>
          )}
        </ScrollView>
      </View>
    </PageContainer>
  );
};

const styles = StyleSheet.create({});

// 导出函数式组件
export default Category;
